package day_2022_7_to_8.day48;

import java.util.*;

/**
 * @author haomin
 * @date 2022/07/27 09:53
 **/
public class Day12_2_Num451_FrequencySort {
    // 1. 创建一个类，属性有 字符和该字符出现次数
    static class Element {
        private char name;
        private int count;

        public Element(char name, int count) {
            this.name = name;
            this.count = count;
        }
    }
    public String frequencySort(String s) {
        // 2. 创建一个map 统计每个字符出现次数
        Map<Character, Integer> map = new HashMap<>();
        for(int i = 0;i <= s.length();i++){
            char a = s.charAt(i);
            if(map.containsKey(a)) {
                map.replace(a,map.get(a) + 1);
            }else {
                map.put(a,1);
            }
        }
        // 3. 将map 中的Key-Value 以Element对象存入ArrayList
        ArrayList<Element> list = new ArrayList<>();
        Set<Map.Entry<Character, Integer>> entries = map.entrySet();
        for (Map.Entry<Character, Integer> entry : entries) {
            list.add(new Element(entry.getKey(),entry.getValue()));
        }
        // 4. 重写Comparator 方法 对list 进行排序
        Collections.sort(list, new Comparator<Element>() {
            @Override
            public int compare(Element o1, Element o2) {
                return o2.count - o1.count;
            }
        });
        // 5. 遍历拼接字符串
        String result = "";
        for (Element element : list) {
            for(int i = 0;i < element.count;i++){
                result += element.name;
            }
        }
        return result;
    }
}